import traceback

from flask import jsonify
from werkzeug.http import HTTP_STATUS_CODES

from .result import Result
from .status import ResponseStatus


def register_errors(app):

    @app.errorhandler(404)
    def notfound_error(e):
        return api_abort(ResponseStatus.NOT_FOUND.code, ResponseStatus.NOT_FOUND.msg)

    @app.errorhandler(AuthFailed)
    def auth_error(e):
        return api_abort(ResponseStatus.UNAUTHORIZED.code, e.args[0])

    @app.errorhandler(Exception)
    def error_500(ex):
        """这个handler可以catch住所有的abort(500)和raise exeception."""
        traceback.print_exc()

        return Result.faild(ResponseStatus.INTERNAL_SERVER_ERROR.code, repr(ex))

    @app.errorhandler(ValidationError)
    def validation_error(e):
        return api_abort(400, e.args[0])


def api_abort(code, message=None, **kwargs):
    if message is None:
        message = HTTP_STATUS_CODES.get(code, '')

    return Result.faild(code, message)


class AuthFailed(ValueError):
    pass


class ValidationError(ValueError):
    pass

# 简单列了一些，别的类型自己可以根据需要扩展补充




